package com.zeny.xdclass.interceptor;

import com.google.gson.Gson;
import com.zeny.xdclass.common.ResponseResult;
import com.zeny.xdclass.utils.CookieUtils;
import com.zeny.xdclass.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @ClassName LoginIntercepter
 * @Description 登录拦截器
 * @Author zeny
 */
@Component
public class LoginIntercepter implements HandlerInterceptor {

    private static final Gson gson = new Gson();

    /**
     * @param request
     * @param response
     * @param handler
     * @return boolean
     * @Description 拦截访问
     **/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = CookieUtils.getCookieValue(request, "token");
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
            if (StringUtils.isNotBlank(token)) {
                CookieUtils.setCookie(request, response, "token", token, 60 * 60 * 24 * 7, "UTF-8");
            }
        }
        if (StringUtils.isNotBlank(token)) {
            Claims claims = JwtUtils.checkToken(token);
            if (claims != null) {
                Integer id = (Integer) claims.get("id");
                String name = (String) claims.get("name");
                request.setAttribute("id", id);
                request.setAttribute("name", name);
                return true;
            }
        }
        sendJsonMessage(response, ResponseResult.auth());
        return false;
    }

    /**
     * @param response
     * @param obj
     * @return void
     * @Description 响应数据给前端
     **/
    private void sendJsonMessage(HttpServletResponse response, Object obj) {
        PrintWriter writer = null;
        try {
            response.setContentType("application/json;charset=utf-8");
            writer = response.getWriter();
            writer.println(gson.toJson(obj));
            response.flushBuffer();
        } catch (Exception e) {
        } finally {
            if (writer != null) {
                writer.close();
            }
        }

    }
}
